package datafloweditor.engine.core;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

import org.apache.log4j.Logger;

import dataflowScheme.SynchroPort;

public class Stopper implements ConnectableEntity {

	private final CountDownLatch doneSignal;
	private final dataflowScheme.Stopper eStopper;
	
	private Set<String> ports = new HashSet<String>();
//	private Map<String, ConnectionAnchor> conns = new HashMap<String, ConnectionAnchor>();
	private Set<String> fullPorts = new HashSet<String>();

	static Logger log = Logger.getLogger(Stopper.class);
	
	public Stopper(dataflowScheme.Stopper eStopper, CountDownLatch doneSignal) {
		this.doneSignal = doneSignal;
		this.eStopper = eStopper;
	}
	
	public void init(){
		for(SynchroPort p : eStopper.getPorts()){
			ports.add(p.getName());
		}
	}
	
	@Override
	public void addConnection(String portName,
			ConnectableEntity oppossiteEntity, String oppossitePortName) {
//		if(ports.contains(portName)){
//			conns.put(portName, new ConnectionAnchor(oppossiteEntity, oppossitePortName));
//		}		
	}

	private void run(){
		doneSignal.countDown();
	}
	
	@Override
	public boolean receiveData(Object data, String portName) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void receiveResponse(EventMsg event, String portName) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean receiveSignal(String portName) {
		if(!ports.contains(portName)){
			log.error("Trying to set data to unknown port '" + portName + "'.");
			return false;
		}
		
		if(fullPorts.contains(portName)){
			//we have a token, therefore reject attempt of sender
			return false;
		} else {
			fullPorts.add(portName);
		}

		if(fullPorts.size() == ports.size()){
			//going down, bye bye
			run();
		}
		
		return true;
	}



}
